<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: swc
 * @Date: 2023-10-17 09:59:26
 * @LastEditors: zss
 * @LastEditTime: 2024-07-04 16:10:41
-->
<template>
  <div class="init-container">
    <div class="mask-container" v-if="isMask"></div>
    <div class="none-container" v-if="nonePermission">
      {{ $srv.getI18nByPath('others.noPermissions') }}···
    </div>
    <div class="main">
      <o-simple-toolbar
        :list="toolbarList"
        bgColor="var(--theme-color-frame)"
        align="center"
        @click="btnClick"
      />
      <div class="body y-scroll">
        <Collapse v-model="activePanel">
          <template v-for="(fun, id) of multiTables">
            <Panel :name="fun.funName" :key="id">
              {{ $srv.getI18nBySrv(fun.funName) }}
              <template #content>
                <div class="forms">
                  <div
                    class="form-item"
                    v-for="(rowNum, idx) of fun.formRows"
                    :key="idx"
                  >
                    <o-base-form
                      :ref="fun.funName + idx"
                      :adaptivelayout="formItemWigth"
                      :mode="1"
                      @compBoxInfo="formIsMounted(fun.funName, idx, $event)"
                      @on-change="
                        receiveBaseFormDataChange(fun.funName, idx, $event)
                      "
                    />
                    <div class="forms-item-btn">
                      <Button
                        @click="handleDelete(fun.funName, idx)"
                        shape="circle"
                        icon="md-trash"
                      />
                    </div>
                  </div>
                  <div
                    class="forms-bottom-btn ivu-icon ivu-icon-md-add"
                    @click="handleInsert(fun.funName, fun.formRows)"
                    :class="[{ disabled: true }]"
                  ></div>
                </div>
              </template>
            </Panel>
          </template>
        </Collapse>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {
  Tsrv,
  T_srv,
  ifs,
  ts,
  vue,
  I_cmd,
  T_cmd,
  N_oMultiForm,
  toolbarList,
  N_oSimpleToolbar,
  N_oSetupPanel
} from './config';

@T_srv.comp({
  components: {}
})
export default class oMultiForm extends vue {
  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  config: any;

  // _config副本 这样不会改到store里的数据
  private _config: any = null;

  /* 组件名 */
  private name: string = 'oMultiForm';

  private G_compName: string = this.name;

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  /* 指挥部 */
  private GT_command: I_cmd = new T_cmd();

  private multiTables: Array<N_oMultiForm.I_openFunParams> = [];

  private custEventID: string = Tsrv.utils.custUUID(10, 16);

  // private toolbar = this.GT_command.toolbarCfg;
  public toolbarList: Array<N_oSimpleToolbar.I_Conf> = toolbarList() ?? [];

  private editStatus: boolean = false;

  private originalData: any;

  private filter: object;

  public isMask: boolean = false;

  private nonePermission: boolean = false;

  public funName: string = '';

  public currentMsg: any = null;

  get activePanel(): Array<string> {
    return this.multiTables.map(item => item.funName);
  }

  // set activePanel(value: Array<string>) {

  // }

  get formItemWigth() {
    return this.getFormItemWigth();
  }

  created() {
    this._config = Tsrv.utils.clone(this.config, true);
    // 如果父组件没有传参，那就产生一个
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    this.GT_command.init(this, this.GT_compBoxInfo);
    this.GT_command.newTcompCoordination(this._config);
    this.init();
  }

  mounted() {
    /* 向父组件发送实例 */
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    this.$emit('compBoxInfo', this.GT_compBoxInfo);
    /* 最终应用组件向外抛出引用实例,以供应用间调用 */
    Tsrv.compBox.addCompMergeName(
      Tsrv.compBox.getDefGUID(), // 全局compBox
      this.funName,
      this
    );
    this.getDefListener();
    // if (
    //   !Tsrv.utils.noValue(this._config?.messageConfig?.custDefListener?.search)
    // ) {
    //   this.$bus.$on(
    //     this._config?.messageConfig?.custDefListener.search[0],
    //     (m: any) => {
    //       const filter = {
    //         [m.content.ukey]: { $in: m?.content?.val }
    //       };
    //       this.GT_command.setFilter(filter);
    //       this.GT_command.loadData();
    //     }
    //   );
    // }
    if (this._config?.messageConfig?.custDefListener?.coordination) {
      this.$bus.$on(
        this._config.messageConfig.custDefListener.coordination,
        msg => {
          this.GT_command.receEventCoordination(msg);
        }
      );
    }
  }

  beforeDestroy() {}

  destroyed() {
    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);

    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
    /* 最终应用组件销毁 */
    Tsrv.compBox.removeCompMergeName(Tsrv.compBox.getDefGUID(), this.funName);
    if (this._config?.messageConfig?.custDefListener?.coordination) {
      this.$bus.$off(this.config.messageConfig.custDefListener.coordination);
    }
    if (
      !Tsrv.utils.noValue(this._config?.messageConfig?.custDefListener?.search)
    ) {
      this.$bus.$off(this._config?.messageConfig?.custDefListener.search[0]);
    }
  }

  private init() {
    this.funName = this.config?.name || '';
    this.GT_command.newTcompCoordination(this.config);
    if (this._config) {
      if (Tsrv.utils.noValue(this._config.multiTables)) {
        return;
      }
      this.GT_command.initToolbar(this._config);
      Promise.all(
        this._config.multiTables.map(e => {
          return this.$store.dispatch('getLayoutConfigAsync', {
            funid: null,
            field: e.value.toTable,
            type: 'component'
          });
        })
      )
        .then(res => {
          res.forEach(e => {
            this.multiTables.push({
              show: this.multiTables.length === 0,
              conf: this.getCompConfig(e.current.config),
              funName: e.current.config.name,
              // tableColumns: this.getTableColumns(e.current.config.name),
              tableColumns: e.current.config.tableColumns,
              formRows: [],
              tableName: e.current.config.name,
              dbType: e.current.config.dbType,
              openCompName:
                e.current.name === 'BaseGrid'
                  ? Tsrv.utils.findComponent(e.current.name)
                  : ''
            });
            this.GT_command.initFormData(e.current.config.name);
          });
          if (Tsrv.getx(this._config, 'tableDataSetting.autoload', true)) {
            this.GT_command.loadData();
          }
        })
        .catch(e => {
          console.error('请求数据出错', e);
          // this.$msg(Tsrv.getI18nByValue('多表from:请求数据出错'));
        });

      // 功能“浏览”权限
      const defaultPermission = Tsrv.utils.find(
        this._config.permission,
        item => item.area === 'default'
      );
      this.nonePermission = !defaultPermission?.data?.browse;
    }
  }

  getCompConfig(cf: any): any {
    if (Tsrv.utils.noValue(cf)) {
      return null;
    }
    const _cf = Tsrv.utils.clone(cf, true);
    _cf.messageConfig.custDefListener['search'] = [this.custEventID];
    _cf.tableDataSetting.autoload = false;
    return _cf;
  }

  public btnClick(btn: N_oSimpleToolbar.I_Conf, e: any) {
    switch (btn.key) {
      case 'edit':
        this.edit();
        break;
      case 'save':
        this.save();
        break;
      case 'refresh':
        this.refresh();
        break;
      // case 'expand':
      //   // this.expand();
      //   break;
      default:
        break;
    }
  }

  private edit() {
    // const button = Tsrv.utils.find(this.toolbarList, el => el.key === 'edit');
    if (this.editStatus) {
      this.editStatus = false;
      this.GT_command.setToolbarStyle('edit', {
        title: Tsrv.getI18nByValue('编辑'),
        class: 'wy-bianji1'
      });

      this.GT_command.setModify(false);
    } else {
      this.editStatus = true;
      this.GT_command.setToolbarStyle('edit', {
        title: Tsrv.getI18nByValue('取消编辑'),
        class: 'wy-yiquxiao'
      });

      this.GT_command.setModify(true);
    }
  }

  private save() {
    this.GT_command.handleSave();
  }

  private refresh() {
    this.GT_command.loadData();
    // 更新按钮状态
    this.editStatus = false;
    this.setToolbarStatus();
  }

  // 新增form
  private handleInsert(funName: any, formRows: any) {
    this.GT_command.handleInsert(funName, formRows);
  }

  // 删除 formItem
  private handleDelete(funName: any, idx: any) {
    this.$Modal.confirm({
      title: Tsrv.getI18nByPath('prompt.isDeleteData') as string,
      content: Tsrv.getI18nByPath('prompt.deleteData') as string,
      onOk: () => {
        // 删除前后
        this.GT_command.handleDelete(funName, idx);
      }
    });
  }

  // 更新toobar 按钮状态
  public setToolbarStatus() {
    if (this.editStatus) {
      this.GT_command.setToolbarStyle('edit', {
        title: Tsrv.getI18nByValue('取消编辑'),
        class: 'wy-yiquxiao'
      });
    } else {
      this.GT_command.setToolbarStyle('save', 'disabled', true);
      this.GT_command.setToolbarStyle('edit', {
        title: Tsrv.getI18nByValue('编辑'),
        class: 'wy-bianji1'
      });
    }
  }

  // 监听测试
  private receiveBaseFormDataChange(funName: string, idx: number, e: any) {
    this.GT_command.listenDataChange(funName, idx, e);
  }

  formIsMounted(funName: string, rowIdx: number, e: any) {
    this.GT_command.setFunForms(funName, rowIdx, e);
  }

  private getDefListener() {
    const custDefListener = this._config?.messageConfig?.custDefListener;
    if (
      !Tsrv.utils.noValue(this._config?.messageConfig?.custDefListener?.search)
    ) {
      this.$bus.$on(
        this._config?.messageConfig?.custDefListener.search[0],
        (m: any) => {
          this.currentMsg = m;
          let filter = {};
          const autoCompleteInfo: any = m.option.autoCompleteInfo;
          if (autoCompleteInfo?.defaultVal) {
            // filter = {
            //   node_id: { $in: autoCompleteInfo.defaultVal[0].value }
            // };
            filter = {
              $and: [
                { [m.content.ukey]: m?.content?.val[0] },
                { node_id: autoCompleteInfo.defaultVal[0].value }
              ]
            };
          } else {
            filter = {
              [m.content.ukey]: { $in: m?.content?.val }
            };
          }
          this.filter = filter;
          this.GT_command.setFilter(filter);
          this.GT_command.loadData();
        }
      );
    }
  }

  // 发事件清空子组件数据
  public cleanSubCompData(
    p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
  ) {}

  // 获取表单的宽度
  private getFormItemWigth() {
    const formStyle = this.config?.formStyle;
    let formItemWidth: string;
    if (Tsrv.utils.noValue(formStyle)) {
      formItemWidth = '200px';
    } else {
      if (formStyle.pixelWidth === 0 && formStyle.percentageWidth === 0) {
        formItemWidth = '200px';
      } else if (formStyle.pixelWidth > 0) {
        formItemWidth = `${formStyle.pixelWidth}px`;
      } else {
        formItemWidth = `${formStyle.percentageWidth}%`;
      }
    }
    return formItemWidth;
  }

  // 待完善：
  // 1、保存前/后 验证与事件，2、编辑锁，3、getVal设置默认数据，4、值改变dochange
}
</script>
<style lang="scss" scoped>
.main ::v-deep {
  height: 100%;
  .toolbar {
    background-color: var(--multiform-toolbar-bg-color);

    // 按钮hover状态修改
    .command:hover:not(.disable) {
      color: var(--multiform-toolbar-hover-font-color);
    }
  }
  .body {
    height: 100%;
    padding-bottom: 40px;
    .forms {
      display: flex;
      flex-direction: column;
      height: 100%;
      ::v-deep .form-item {
        margin-bottom: 10px;
        box-shadow: 0 2px 10px #8888883b;
        display: flex;

        // .vxe-form {
        //   min-width: 200px;
        // }

        .main {
          flex: 1;
        }

        .forms-item-btn {
          display: flex;
          align-items: center;
        }
      }
      .forms-bottom-btn {
        margin-left: 50%;
        margin-bottom: 10px;
        margin-left: 50%;

        width: 20px;
        height: 15px;
        border: 1px solid #eaebef;
        cursor: pointer;
        border-radius: 0 0 10px 10px;
        border-top: none;
        box-shadow: 0 2px 10px #888888;
        color: #2d8eff;
      }
    }
  }
}
</style>
